package com.vehicle.repair.service;

import com.vehicle.repair.model.Repairer;
import com.vehicle.repair.model.WorkLog;
import com.vehicle.repair.model.WorkOrder;
import com.vehicle.repair.repository.WorkLogRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class WorkLogService {
    private final WorkLogRepository workLogRepository;
    private final WorkOrderService workOrderService;
    private final RepairerService repairerService;

    public WorkLogService(WorkLogRepository workLogRepository,
                        WorkOrderService workOrderService,
                        RepairerService repairerService) {
        this.workLogRepository = workLogRepository;
        this.workOrderService = workOrderService;
        this.repairerService = repairerService;
    }

    public WorkLog addWorkLog(WorkLog workLog, Integer orderId, Integer repairerId) {
        WorkOrder order = workOrderService.getWorkOrderById(orderId)
                .orElseThrow(() -> new IllegalArgumentException("Work order not found"));
        
        Repairer repairer = repairerService.getRepairerById(repairerId)
                .orElseThrow(() -> new IllegalArgumentException("Repairer not found"));
        
        workLog.setOrder(order);
        workLog.setRepairer(repairer);
        
        return workLogRepository.save(workLog);
    }

    public Optional<WorkLog> getWorkLogById(Integer id) {
        return workLogRepository.findById(id);
    }

    public List<WorkLog> getWorkLogsByOrder(Integer orderId) {
        WorkOrder order = workOrderService.getWorkOrderById(orderId)
                .orElseThrow(() -> new IllegalArgumentException("Work order not found"));
        return workLogRepository.findByOrder(order);
    }

    public List<WorkLog> getWorkLogsByRepairer(Integer repairerId) {
        Repairer repairer = repairerService.getRepairerById(repairerId)
                .orElseThrow(() -> new IllegalArgumentException("Repairer not found"));
        return workLogRepository.findByRepairer(repairer);
    }

    public void deleteWorkLog(Integer id) {
        workLogRepository.deleteById(id);
    }
}
